package com.cy.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cy.server.pojo.Employee;
import com.cy.server.pojo.MailConstants;
import com.cy.server.pojo.MailLog;
import com.cy.server.service.IEmployeeService;
import com.cy.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @peoject: yeb
 * @description: 邮件定时发送任务
 * @author: LiShaoZhuo
 * @create: 2021-05-08 14:30
 **/
@Component
public class EmailTask {

    @Autowired
    IMailLogService mailLogService;
    @Autowired
    IEmployeeService employeeService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * @Description: 邮件发送定时任务 每10秒一次
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/5/8
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void emailTask(){
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));
        list.forEach(mailLog -> {
            //如果重试次数超过三次，更新状态为投递失败，不再重试
            if (mailLog.getCount() >= 3){
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status", 2)
                        .eq("msgId", mailLog.getMsgId()));
            }
            //投递一次后，投递次数+1，尝试时间+1
            mailLogService.update(new UpdateWrapper<MailLog>()
                    .eq("count", mailLog.getCount()+1)
                    .set("updateTime",LocalDateTime.now())
                    .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .set("msgId", mailLog.getMsgId()));
            Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
            //发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME,
                    employee, new CorrelationData(mailLog.getMsgId()));
        });
    }
}
